<template>
  <div class="home-container">
    <!-- 顶部栏 -->
    <div class="top-bar">
      <div class="top-left">
        <img src="../assets/logo.png" alt="系统Logo" class="logo" />
        <span class="title">皮革产品打样需求管理系统</span>
      </div>
      <div class="search-container">
        <input
            type="text"
            v-model="searchQuery"
            placeholder="搜索项目名称、客户名称、公司名称、创建时间..."
            class="search-input"
        />
        <button class="search-button">
          <i class="iconfont icon-search"></i>
        </button>
      </div>
      <div class="buttons">
        <button class="primary-button" @click="createNewProject">
          <i class="iconfont icon-add"></i> 新建项目
        </button>
      </div>
      <div class="logout-button-container">
        <button class="logout-button" @click="logout">
          <i class="iconfont icon-exit"></i> 退出
        </button>
      </div>
    </div>
    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 左侧面板 -->
      <div class="left-panel">
        <div class="scroll-panel">
          <div
              class="project-card"
              v-for="project in projects"
              :key="project.id"
              @click="viewProject(project.id)"
          >
            <div class="project-content">
              <h3>{{ project.projectName }}</h3>
              <div class="project-meta">
                <span><i class="iconfont icon-ID"></i> {{ project.projectCode }}</span>
                <span><i class="iconfont icon-date"></i> {{ formatDate(project.createTime) }}</span>
                <span><i class="iconfont icon-creater"></i> {{ project.createUser.name }} </span>
                <span><i class="iconfont icon-status"></i> {{ getStatusText(project.status) }}</span>
              </div>
            </div>
            <div class="project-actions">
              <button class="icon-button danger" @click.stop="deleteProject(project.id)">
                <i class="iconfont icon-delete"></i>
              </button>
            </div>
          </div>
        </div>
      </div>
      <!-- 右侧面板 -->
      <div class="right-panel">
        <!-- 用户信息卡片 -->
        <div class="user-profile">
          <div class="avatar">
            <i class="iconfont icon-user"></i>
          </div>
          <h3>{{ user.name }}</h3>
          <p class="position">{{ user.position }}</p>
          <div class="user-info">
            <div class="info-item">
              <i class="iconfont icon-department"></i>
              <span>{{ user.department || '未设置' }}</span>
            </div>
            <div class="info-item">
              <i class="iconfont icon-phone"></i>
              <span>{{ user.phone || '未设置' }}</span>
            </div>
          </div>
        </div>
        <!-- 产品统计可视化模块 -->
        <div class="stats-card">
          <h3 class="stats-title">产品统计</h3>
          <div class="chart-container">
            <canvas ref="productChart"></canvas>
          </div>
          <div class="stats-summary">
            <div class="summary-item">
              <i class="iconfont icon-project"></i>
              <span>总项目数: {{ stats.totalProjects }}</span>
            </div>
            <div class="summary-item completed">
              <i class="iconfont icon-completed"></i>
              <span>已完成: {{ stats.completedProjects }}</span>
            </div>
            <div class="summary-item pending">
              <i class="iconfont icon-pending"></i>
              <span>进行中: {{ stats.pendingProjects }}</span>
            </div>
<!--            <div class="summary-item canceled">-->
<!--              <i class="iconfont icon-canceled"></i>-->
<!--              <span>已取消: {{ stats.canceledProjects }}</span>-->
<!--            </div>-->
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import Chart from 'chart.js/auto';
import { ref } from 'vue';

const searchQuery = ref('');

export default {
  data() {
    return {
      windowHeight: 0,
      projects: [],
      user: {
        name: '加载中...',
        position: '',
        phone: '',
        department: '',
      },
      searchQuery: '',
      originalProjects: [],
      stats: {
        totalProjects: 0,
        completedProjects: 0,
        pendingProjects: 0,
        canceledProjects: 0,
        chartData: {
          labels: ['已完成', '进行中', '已取消'],
          datasets: [{
            data: [0, 0, 0],
            backgroundColor: [
              'rgba(75, 192, 192, 0.7)', // 已完成
              'rgba(255, 99, 132, 0.7)', // 未完成
              'rgba(255, 206, 86, 0.7)'  // 已取消
            ],
            borderColor: [
              'rgba(75, 192, 192, 1)',
              'rgba(255, 99, 132, 1)',
              'rgba(255, 206, 86, 1)'
            ],
            borderWidth: 1
          }]
        }
      },
      productChart: null
    };
  },
  mounted() {
    this.getWindowHeight();
    window.addEventListener('resize', this.getWindowHeight);
    this.fetchUserInfo().then(() => {
      this.fetchProjects().then(() => {
        this.$nextTick(() => {
          if (this.$refs.productChart) {
            this.initChart();
          }
        });
      });
    });
  },
  watch: {
    searchQuery(newVal) {
      this.handleSearch();
    },
    projects: {
      handler(newProjects) {
        this.updateStats(newProjects);
      },
      deep: true
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.getWindowHeight);
    if (this.productChart) {
      try {
        this.productChart.destroy();
      } catch (error) {
        console.error('销毁图表时出错:', error);
      }
      this.productChart = null;
    }
  },
  methods: {
    getWindowHeight() {
      this.windowHeight = window.innerHeight;
    },
    async fetchProjects() {
      const token = localStorage.getItem('token');
      try {
        const response = await axios.get('/api/projects', {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });
        // alert(JSON.stringify(response.data.data, null, 2));
        console.log(response.data.data);
        this.projects = response.data.data || [];
        this.originalProjects = [...this.projects];
        return Promise.resolve();
      } catch (error) {
        this.$notify.error({
          title: '错误',
          message: '获取项目列表失败',
        });
        return Promise.reject(error);
      }
    },
    async fetchUserInfo() {
      const token = localStorage.getItem('token');
      try {
        const response = await axios.get('/api/auth/current', {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });
        this.user = response.data.data;
      } catch (error) {
        this.$notify.error({
          title: '错误',
          message: '获取用户信息失败',
        });
      }
    },
    updateStats(projects) {
      try {
        if (!Array.isArray(projects)) {
          console.warn('projects不是数组', projects);
          return;
        }

        const completed = projects.filter(p => p.status === 2).length;
        const pending = projects.filter(p => p.status === 1).length;
        const canceled = projects.filter(p => p.status === 0).length;
        const total = projects.length;

        const newChartData = {
          labels: ['已完成', '进行中'],
          datasets: [{
            data: [completed, pending],
            backgroundColor: [
              'rgba(75, 192, 192, 0.7)',
              'rgba(255, 99, 132, 0.7)'
            ],
            borderColor: [
              'rgba(75, 192, 192, 1)',
              'rgba(255, 99, 132, 1)'
            ],
            borderWidth: 1
          }]
        };

        this.stats = {
          totalProjects: completed + pending + canceled,
          completedProjects: completed,
          pendingProjects: pending,
          canceledProjects: canceled,
          chartData: newChartData
        };

        this.$nextTick(() => {
          if (this.$refs.productChart) {
            if (!this.productChart) {
              this.initChart();
            } else {
              try {
                this.productChart.data.labels = newChartData.labels;
                this.productChart.data.datasets = newChartData.datasets;
                this.productChart.update('none'); // 使用 'none' 避免动画冲突
              } catch (chartError) {
                console.error('更新图表时出错:', chartError);
                this.initChart();
              }
            }
          }
        });
      } catch (error) {
        console.error('更新统计时出错:', error);
      }
    },
    initChart() {
      try {
        if (!this.$refs.productChart) {
          console.warn('Canvas元素未找到');
          return;
        }

        const ctx = this.$refs.productChart.getContext('2d');
        if (!ctx) {
          console.warn('无法获取Canvas上下文');
          return;
        }

        if (this.productChart) {
          try {
            this.productChart.destroy();
          } catch (e) {
            console.warn('销毁旧图表失败:', e);
          }
        }

        this.productChart = new Chart(ctx, {
          type: 'doughnut',
          data: JSON.parse(JSON.stringify(this.stats.chartData)), // 深拷贝数据
          options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
              legend: {
                position: 'right',
                labels: {
                  color: 'white',
                  font: {
                    size: 12
                  }
                }
              }
            },
            cutout: '70%',
            animation: {
              animateScale: true,
              animateRotate: true
            },
            devicePixelRatio: 1,
            onResize: null
          }
        });
      } catch (error) {
        console.error('初始化图表时出错:', error);
      }
    },
    handleSearch() {
      if (!this.searchQuery.trim()) {
        this.projects = [...this.originalProjects];
        return;
      }

      const query = this.searchQuery.toLowerCase();
      this.projects = this.originalProjects.filter(project => {
        return (
            (project.projectName && project.projectName.toLowerCase().includes(query)) ||  // 项目名称
            (project.clientName && project.clientName.toLowerCase().includes(query)) ||   // 公司名称
            (project.clientContact && project.clientContact.toLowerCase().includes(query)) ||  // 客户名称
            (project.projectCode && project.projectCode.toLowerCase().includes(query)) ||  // 项目编号
            (project.createTime && project.createTime.toLowerCase().includes(query))  // 创建时间
        );
      });
    },
    formatDate(dateString) {
      if (!dateString) return '未知日期';
      const date = new Date(dateString);
      return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
    },
    getStatusText(status) {
      switch (status) {
        case 0:
          return '已取消';
        case 1:
          return '进行中';
        case 2:
          return '已完成';
        default:
          return '未知状态';
      }
    },
    createNewProject() {
      this.$router.push('/projects/new');
    },
    viewProject(projectId) {
      this.$router.push(`/projects/${projectId}`);
    },
    async deleteProject(projectId) {
      try {
        await this.$confirm('确定要删除这个项目吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });

        const token = localStorage.getItem('token');
        await axios.delete(`/api/projects/${projectId}`, {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });

        this.$notify.success({
          title: '成功',
          message: '项目已删除',
        });
        this.fetchProjects();
      } catch (error) {
        if (error !== 'cancel') {
          this.$notify.error({
            title: '错误',
            message: '删除项目失败',
          });
        }
      }
    },
    logout() {
      this.$confirm('确定要退出登录吗？', '安全提示', {
        confirmButtonText: '退出登录',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
        customClass: 'logout-confirm',
        distinguishCancelAndClose: true,
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            instance.confirmButtonText = '正在退出...';
            setTimeout(() => {
              this.performLogout();
              done();
            }, 500);
          } else {
            done();
          }
        }
      }).catch(action => {
        if (action === 'cancel') {
          this.$message({
            type: 'info',
            message: '已取消退出',
            duration: 1000
          });
        }
      });
    },
    performLogout() {
      const loading = this.$loading({
        lock: true,
        text: '正在安全退出...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      localStorage.removeItem('token');
      localStorage.removeItem('rememberedUsername');
      sessionStorage.clear();

      if (this.$store) {
        this.$store.commit('resetAuthState');
      }

      this.projects = [];
      this.user = {
        name: '',
        position: '',
        phone: '',
        department: ''
      };

      this.$router.push('/login').then(() => {
        this.$notify.success({
          title: '已退出',
          message: '您已安全退出系统',
          duration: 2000,
          offset: 50
        });
      }).catch(err => {
        console.error('路由跳转失败:', err);
      }).finally(() => {
        loading.close();
      });
    },
  },
};
</script>

<style scoped>
@import url('/icon/font_4949155_5og69jvvyjb/iconfont.css');

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  @font-face {
    font-family: "SanFont"; /* 自定义字体名称 */
    src: url('/fonts/san.ttf') format('truetype'); /* 指定字体文件路径和格式 */
  }
}

html, body {
  height: 100%;
  overflow: hidden;
}

.home-container {
  display: flex;
  flex-direction: column;
  height: 95vh;
  background: #f8f9fa;
}

.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 25px;
  height: 70px;
  background: white;
  border-bottom: 1px solid #ebebeb;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.8);
}

.top-left {
  display: flex;
  align-items: center;
}

.logo {
  width: 50px;
  height: 50px;
  margin-right: 20px;
}

.title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  background: linear-gradient(45deg, #6a11cb, #2575fc);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.search-container {
  display: flex;
  align-items: center;
  margin-right: 20px;
  flex-grow: 1;
  max-width: 400px;
}

.search-input {
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  width: 100%;
  transition: all 0.3s;
  background: rgba(255, 255, 255, 0.8);
}

.search-input:focus {
  outline: none;
  border-color: #6a11cb;
  box-shadow: 0 0 0 2px rgba(106, 17, 203, 0.2);
}

.search-button {
  background: none;
  border: none;
  cursor: pointer;
  margin-left: -35px;
  color: #6a11cb;
  transition: all 0.3s;
}

.search-button:hover {
  color: #2575fc;
}

.search-button i {
  font-size: 18px;
}

.primary-button {
  padding: 10px 20px;
  background: linear-gradient(to right, #6a11cb 0%, #2575fc 100%);
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
}

.primary-button i {
  margin-right: 8px;
}

.primary-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(106, 17, 203, 0.3);
}

.logout-button-container {
  display: flex;
  align-items: center;
}

.logout-button {
  padding: 8px 15px;
  background: rgba(255, 255, 255, 0.2);
  color: #333;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
}

.logout-button i {
  margin-right: 8px;
}

.logout-button:hover {
  background: rgba(255, 255, 255, 0.3);
}

.logout-confirm {
  border-radius: 8px;
  padding: 20px;
  width: 420px;
}

.logout-confirm .el-message-box__header {
  border-bottom: 1px solid #eee;
  padding-bottom: 15px;
}

.logout-confirm .el-message-box__content {
  padding: 20px 0;
  color: #606266;
}

/* 加载动画 */
.el-loading-spinner {
  top: 50%;
  transform: translateY(-50%);
}

.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
  background: linear-gradient(
      to right,
      rgba(106, 17, 203, 0.8) 0%,
      rgba(37, 117, 252, 0.6) 100%
  );
}

.left-panel {
  width: 75%;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  padding: 15px;
  background: linear-gradient(
      to right,
      rgba(106, 17, 203, 0.8) 0%,
      rgba(37, 117, 252, 0.6) 100%
  );
}

.scroll-panel {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}

.right-panel {
  width: 25%;
  background: linear-gradient(
      to left,
      rgba(106, 17, 203, 0.8) 0%,
      rgba(37, 117, 252, 0.6) 100%
  );
  color: white;
  display: flex;
  flex-direction: column;
  padding-top: 15px;
  padding-right: 15px;
}

.user-profile {
  background: rgba(255, 255, 255, 0.7);
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px 15px 0 15px;
  border-radius: 8px;
  color: dimgray;
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 5px;
}

.avatar i {
  font-size: 30px;
  color: white;
}

.user-profile h3 {
  font-size: 20px;
  margin-bottom: 5px;
}

.position {
  background: rgba(0, 0, 0, 0.1);
  padding: 5px 15px;
  border-radius: 20px;
  font-size: 14px;
  margin-bottom: 10px;
  color: white;
}

.user-info {
  width: 100%;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  font-size: 14px;
}

.info-item i {
  margin-right: 10px;
  font-size: 16px;
  color: rgba(255, 255, 255, 0.7);
}

.stats-card {
  background: rgba(255, 255, 255, 0.7);
  border-radius: 8px;
  padding: 15px;
  margin-top: 15px;
  color: dimgray;
}

.stats-title {
  text-align: center;
  font-size: 16px;
  color: #333;
  font-weight: 600;
}

.chart-container {
  position: relative;
  margin-left: 15px;
  height: 200px;
  width: 100%;
  min-height: 200px; /* 确保最小高度 */
  overflow: hidden;
  contain: strict;
}

.chart-container canvas {
  display: block;
  width: 100% !important;
  height: 100% !important;
  max-width: 100%;
  max-height: 100%;
}

.stats-summary {
  display: flex;
  flex-direction: row;
  gap: 10px;
}

.summary-item {
  display: flex;
  align-items: center;
  font-size: 12px;
  margin-left: 5px;
  padding: 5px 5px;
  background: rgba(255, 255, 255, 0.5);
  border-radius: 6px;
}

.summary-item i {
  margin-right: 8px;
  color: #6a11cb;
}

.project-card {
  background: white;
  border-radius: 10px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s;
  border-left: 4px solid #6a11cb;
}

.project-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.6);
}

.project-content h3 {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin-bottom: 10px;
}

.project-meta {
  display: flex;
  gap: 20px;
  font-size: 10px;
  color: #666;
}

.project-meta i {
  margin-right: 5px;
  color: #6a11cb;
}

.project-actions {
  display: flex;
  gap: 10px;
}

.icon-button {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  border: none;
  background: #f5f5f5;
  color: #666;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
}

.icon-button:hover {
  background: #eee;
}

.icon-button.danger {
  color: #ff4d4f;
}

.icon-button.danger:hover {
  background: rgba(255, 77, 79, 0.1);
}

@media (max-width: 992px) {
  .home-container {
    flex-direction: column;
  }

  .main-content {
    flex-direction: column;
  }

  .search-container {
    order: 1;
    width: 100%;
    max-width: 100%;
    margin: 15px 0;
  }

  .top-bar {
    flex-wrap: wrap;
    padding: 15px;
    height: auto;
  }

  .top-left {
    width: 100%;
    margin-bottom: 15px;
  }

  .buttons {
    order: 2;
    margin-right: 15px;
  }

  .logout-button-container {
    order: 3;
  }

  .left-panel,
  .right-panel {
    width: 100%;
  }

  .right-panel {
    order: -1;
    height: auto;
    padding-bottom: 20px;
  }

  .stats-card {
    margin-top: 15px;
  }

  .chart-container {
    height: 180px;
  }

  .logout-confirm {
    width: 90%;
    max-width: 300px;
  }

  .logout-confirm .el-message-box__content {
    font-size: 14px;
  }

  .logout-confirm .el-message-box__btns button {
    padding: 8px 15px;
    font-size: 14px;
  }
}
</style>